package com.day240701.dao;

import com.day240701.entity.Blog;
import com.day240701.util.JDBCUtils;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class BlogDao {
    /**
     * 添加博文
     * @param title 标题
     * @param content 博文内容
     * @return 是否添加成功
     */
    public boolean addBlog(String title, String content) {
        String sql = "insert into t_blog(blog_title,blog_content) values(?,?)";
        int count = JDBCUtils.doUpdate(sql, title, content);
        return count > 0;
    }

    /**
     * 查询所有博文
     * @return 博文集合
     */
    public List<Blog> queryAllBlogs(){
        String sql = "select blog_id,blog_title,blog_content from t_blog";
        ResultSet rs = JDBCUtils.doQuery(sql);
        List<Blog> blogs = new ArrayList<>();

        try {
            while (rs.next()){
                int blog_id = rs.getInt("blog_id");
                String blog_title = rs.getString("blog_title");
                String blog_content = rs.getString("blog_content");
                blogs.add(new Blog(blog_id,blog_title,blog_content));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.doClose(rs);
        }
        return blogs;

    }

    public Blog queryBlogById(int id) {
        String sql = "select blog_id,blog_title,blog_content from t_blog where blog_id = ?";
        ResultSet rs = JDBCUtils.doQuery(sql, id);
        Blog blog = null;

        try{
            if (rs.next()){
                blog = new Blog();
                blog.setBlogId(rs.getInt("blog_id"));
                blog.setBlogTitle(rs.getString("blog_title"));
                blog.setBlogContent(rs.getString("blog_content"));
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            JDBCUtils.doClose(rs);
        }
        return blog;
    }

    public static void main(String[] args) {
        BlogDao blogDao = new BlogDao();
        System.out.println(blogDao.queryAllBlogs());
    }

}
